package com.aletto.general_store.ui.popup;

import android.content.Context;
import android.content.Intent;

import com.aletto.general_store.R;
import com.aletto.general_store.data.entities.WalletAccount;
import com.aletto.general_store.ui.activities.ProfileActivity;
import com.aletto.general_store.ui.activities.WalletAccountActivity;
import com.aletto.general_store.ui.activities.WalletImportActivity;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.WalletAccountLocalStore;
import com.aletto.general_store.utils.event.ExitEvent;
import com.lxj.xpopup.core.CenterPopupView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import androidx.annotation.NonNull;

public class DeleteWalletPopup extends CenterPopupView {

    private String address;

    public DeleteWalletPopup(@NonNull Context context, String address) {
        super(context);
        this.address = address;
    }

    public DeleteWalletPopup(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.popup_delete_wallet;
    }

    @Override
    protected void onCreate() {
        super.onCreate();

        findViewById(R.id.button_cancel).setOnClickListener(v -> dismiss());

        findViewById(R.id.button_confirm).setOnClickListener(v -> delete());

    }

    private void delete() {
        Context context = getContext();

        // 删除当前账号
        WalletAccountLocalStore.getInstance().removeAccount(address);
        List<WalletAccount> accounts = WalletAccountLocalStore.getInstance().accounts();

        if (accounts != null && !accounts.isEmpty()) {
            // 如果删除钱包为使用钱包，使用往后移动
            WalletAccount useWallet = LocalConfigStore.getInstance().getWallet();
            if (address.equals(useWallet.getAddress())){
                LocalConfigStore.getInstance().setWallet(accounts.get(0));
            }

            // 如果还有账号就跳转到列表
            context.startActivity(new Intent(context, WalletAccountActivity.class));

        } else {

            // 否则跳转到导入页面
            EventBus.getDefault().post(new ExitEvent()); // 退出登录
            context.startActivity(new Intent(context, WalletImportActivity.class));
        }

        dismiss();
        ((ProfileActivity) context).finish();
    }
}
